package controller;

import com.alibaba.fastjson.JSON;
import common.jsondata.IResponseJSONResult;
import common.jsondata.impl.ResponseJSONResultImpl;
import entity.User;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import service.impl.UserServiceImpl;
import util.snowflake.SnowFlake;
import util.snowflake.UUIDGenerator;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * controller返给前端进行一个展示
 */
@Controller
@RequestMapping(value="/items")
public class UserController {
    @Autowired
    private UserServiceImpl userService;

    private static IResponseJSONResult responseJSONResult = new ResponseJSONResultImpl();

    private Logger logger = LoggerFactory.getLogger(UserController.class);

    //跳转登录页
    @RequestMapping("/userinfo")
    public String tologin(){ return  "userinfo/userinfo"; }

    //跳转详情页面
    @RequestMapping("/userdetail")
    //@RequiresRoles("administrator")
    public String userdetail(){ return  "userinfo/userdetail"; }

    //跳转修改页面
    @RequestMapping("/usermodify")
    public String usermodify(){ return  "userinfo/usermodify"; }

    public String checkLogin(HttpServletRequest request, HttpServletResponse response, Model model) throws IOException {
        logger.info("登陆认证开始");
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String email = request.getParameter("email");
        logger.debug("用户名:" + username );
        logger.debug("密码:" + password );
        logger.debug("邮箱:" + password );
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);

        String info = loginUser(user);
        if (!"SUCC".equals(info)) {
            model.addAttribute("failMsg", "用户不存在或密码错误！");
            return "fail";
        }else{
            model.addAttribute("successMsg", "登陆成功！");//返回到页面说夹带的参数
            model.addAttribute("name", user.getUsername());
            return "success";//返回的页面
        }
    }
    private String loginUser(User user) {
        if (isRelogin(user)) return "SUCC"; // 如果已经登陆，无需重新登录

        return shiroLogin(user); // 调用shiro的登陆验证
    }
    private String shiroLogin(User user) {
        // 组装token，包括客户公司名称、简称、客户编号、用户名称；密码
        logger.info("用户信息认证开始");
        UsernamePasswordToken token = new UsernamePasswordToken(user.getUsername(), user.getPassword().toCharArray(), null);
        token.setRememberMe(true);
        // shiro登陆验证
        try {
            SecurityUtils.getSubject().login(token);
        } catch (UnknownAccountException ex) {
            return "用户不存在或者密码错误！";
        } catch (IncorrectCredentialsException ex) {
            return "用户不存在或者密码错误！";
        } catch (Exception ex) {
            ex.printStackTrace();
            return "内部错误，请重试！";
        }
        return "SUCC";
    }

    private boolean isRelogin(User user) {
        Subject us = SecurityUtils.getSubject();
        if (us.isAuthenticated()) {
            return true; // 参数未改变，无需重新登录，默认为已经登录成功
        }
        return false; // 需要重新登陆
    }

    //退出登录
    @RequestMapping(value = "/logout")
    public String logout(HttpServletRequest request,HttpServletResponse response) throws IOException {
        Subject subject = SecurityUtils.getSubject();
        if (subject != null) {
            try{
                subject.logout();
            }catch(Exception ex){

            }
        }
        return "index";
    }

    //查询用户信息
    @ResponseBody
    @RequestMapping(value="/getuser")
    public String getUserInfo(HttpServletRequest request, HttpServletResponse response) throws  Exception{
        List<User> list = userService.findAllUser();
        Map<String,Object> map = new HashMap<>();
        if(list.size() > 0){
            map.put("code",0);
            map.put("msg","查询成功");
            map.put("count",list.size());
            map.put("data",list);
        }else {
            map.put("code",1);
            map.put("msg","未查询到相关数据");
            map.put("count",list.size());
            map.put("data",list);
        }
        logger.debug("数据：" + JSON.toJSONString(map) );
        responseJSONResult.setResponseUTF8(response);
        return JSON.toJSONString(map);
    }

    //新增用户信息
    @RequestMapping(value="/insertuser")
    public String insertuser(HttpServletRequest request, HttpServletResponse response){
        String username = request.getParameter("username");
        //logger.debug("用户名====> " + username);

        String password = request.getParameter("password");
        String age = request.getParameter("age");
        String email = request.getParameter("email");
        String area = request.getParameter("area");
        String phone = request.getParameter("phone");
        String idcard = request.getParameter("idcard");
        //1.设置录入用户的信息
        User user = new User();
        user.setId(UUIDGenerator.getUUID());
        user.setUsername(username);
        user.setPassword(password);
        user.setAge(Integer.valueOf(age));
        user.setEmail(email);
        user.setPhone(phone);
        user.setArea(area);
        user.setIdcard(idcard);
        //2.插入用户信息
        userService.insertOne(user);
        responseJSONResult.setResponseUTF8(response);
        //3.跳转查询页面
        return "redirect:/items/userinfo";
    }

    /**
     * 根据主键删除用户信息
     * @param request
     * @param response
     * @return
     */
    @ResponseBody
    @RequestMapping(value="/deleteuser")
    public String deleteuser(HttpServletRequest request, HttpServletResponse response){
        int count = 0;
        String id = request.getParameter("id");
        if("3267db1e07c84649b1c7a2273ebce895".equals(id)){
            return responseJSONResult.ReturnJSONResunt(response,"超级管理员不可删除！");
        }
        //根据主键删除用户
        count = userService.deleteUserByID(request.getParameter("id"));
        if(count>0){
            return responseJSONResult.ReturnJSONResunt(response,"删除成功(>ω･* )ﾉ");
        }else{
            return responseJSONResult.ReturnJSONResunt(response,"删除失败(╯﹏╰)b");
        }
    }

    /**
     * 根据联合主键删除用户信息
     * @param request
     * @param response
     * @return
     */
    @ResponseBody
    @RequestMapping(value="/deleteuserbyunionid")
    public String deleteUserByUnionId(HttpServletRequest request, HttpServletResponse response){
        int count = 0;
        String[] userList = null;
        //获取待删除用户的主键信息
        String idUnion = request.getParameter("idUnion");
        if(null != idUnion || !"".equals(idUnion)){
            userList = idUnion.split("#");
        }else{
            logger.error("用户主键信息为空或不存在" + idUnion);
            throw new RuntimeException("删除时主键不能为空！");
        }

        //根据主键删除用户
        count = userService.batchDeleteUser(userList);
        if(count>0){
            return responseJSONResult.ReturnJSONResunt(response,"删除成功(>ω･* )ﾉ");
        }else{
            return responseJSONResult.ReturnJSONResunt(response,"删除失败(╯﹏╰)b");
        }
    }

}
